//
//  NewsContentViewController.m
//  SportSocial
//
//  Created by yull on 14/12/24.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "NewsContentViewController.h"
#import "NewsCommentViewController.h"
#import "NewsNet.h"
#import <ShareSDK/ShareSDK.h>

@interface NewsContentViewController ()

@property (nonatomic, strong) NewsModel *news;

@property (nonatomic, strong) UIWebView *webViewNews;

@property (nonatomic, strong) UIView *writeCommentBar;
@property (nonatomic, strong) UITextView *commentTextView;

@end

@implementation NewsContentViewController

- (instancetype)initWithNews:(NewsModel *)news
{
    if (self = [super init]) {
        self.news = news;
    }
    return self;
}

- (void)initToolBar
{
    UIView *toolbar = [[UIView alloc] initWithFrame:CGRectMake(-1, self.view.height - 44, self.view.width + 2, 45)];
    toolbar.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    toolbar.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1];
    toolbar.layer.borderColor = [UIColor grayColor].CGColor;
    toolbar.layer.borderWidth = 1;
    
    if (!self.news.source_type.length) {
        UIButton *writeCommentButton = [UIButton buttonWithType:UIButtonTypeCustom];
        writeCommentButton.frame = CGRectMake(0, 0, 80, 44);
        [writeCommentButton setImage:[UIImage imageNamed:@"news_write_comment.png"] forState:UIControlStateNormal];
        [writeCommentButton setImage:[UIImage imageNamed:@"news_write_comment_selection.png"] forState:UIControlStateHighlighted];
        [writeCommentButton setTitle:@"写评论" forState:UIControlStateNormal];
        [writeCommentButton setTitle:@"写评论" forState:UIControlStateHighlighted];
        [writeCommentButton setTitleColor:[UIColor colorWithRed:89.0/255.0 green:89.0/255.0 blue:89.0/255.0 alpha:1] forState:UIControlStateNormal];
        [writeCommentButton setTitleColor:[UIColor colorWithRed:89.0/255.0 green:89.0/255.0 blue:89.0/255.0 alpha:1] forState:UIControlStateHighlighted];
        [writeCommentButton addTarget:self action:@selector(onClickWriteCommentButton:) forControlEvents:UIControlEventTouchUpInside];
        [toolbar addSubview:writeCommentButton];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(81, 8, 1, 28)];
        lineView.backgroundColor = [UIColor lightGrayColor];
        [toolbar addSubview:lineView];
    }
    
    UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    saveButton.frame = CGRectMake(self.view.width - 70, 0, 70, 44);
    [saveButton setImage:[UIImage imageNamed:@"news_save.png"] forState:UIControlStateNormal];
    [saveButton setImage:[UIImage imageNamed:@"news_save_selection.png"] forState:UIControlStateHighlighted];
    [saveButton setTitle:@"收藏" forState:UIControlStateNormal];
    [saveButton setTitle:@"收藏" forState:UIControlStateHighlighted];
    [saveButton setTitleColor:[UIColor colorWithRed:89.0/255.0 green:89.0/255.0 blue:89.0/255.0 alpha:1] forState:UIControlStateNormal];
    [saveButton setTitleColor:[UIColor colorWithRed:89.0/255.0 green:89.0/255.0 blue:89.0/255.0 alpha:1] forState:UIControlStateHighlighted];
    [saveButton addTarget:self action:@selector(onClickSaveButton:) forControlEvents:UIControlEventTouchUpInside];
    [toolbar addSubview:saveButton];
    
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    shareButton.frame = CGRectMake(self.view.width - 150, 0, 70, 44);
    [shareButton setImage:[UIImage imageNamed:@"news_share.png"] forState:UIControlStateNormal];
    [shareButton setImage:[UIImage imageNamed:@"news_share_selection.png"] forState:UIControlStateHighlighted];
    [shareButton setTitle:@"分享" forState:UIControlStateNormal];
    [shareButton setTitle:@"分享" forState:UIControlStateHighlighted];
    [shareButton setTitleColor:[UIColor colorWithRed:89.0/255.0 green:89.0/255.0 blue:89.0/255.0 alpha:1] forState:UIControlStateNormal];
    [shareButton setTitleColor:[UIColor colorWithRed:89.0/255.0 green:89.0/255.0 blue:89.0/255.0 alpha:1] forState:UIControlStateHighlighted];
    [shareButton addTarget:self action:@selector(onClickShareButton:) forControlEvents:UIControlEventTouchUpInside];
    [toolbar addSubview:shareButton];
    
    if (!self.news.source_type.length) {
        UIButton *commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
        commentButton.frame = CGRectMake(self.view.width - 230, 0, 70, 44);
        [commentButton setImage:[UIImage imageNamed:@"news_comment.png"] forState:UIControlStateNormal];
        [commentButton setImage:[UIImage imageNamed:@"news_comment_selection.png"] forState:UIControlStateHighlighted];
        [commentButton setTitle:@"评论" forState:UIControlStateNormal];
        [commentButton setTitle:@"评论" forState:UIControlStateHighlighted];
        [commentButton setTitleColor:[UIColor colorWithRed:89.0/255.0 green:89.0/255.0 blue:89.0/255.0 alpha:1] forState:UIControlStateNormal];
        [commentButton setTitleColor:[UIColor colorWithRed:89.0/255.0 green:89.0/255.0 blue:89.0/255.0 alpha:1] forState:UIControlStateHighlighted];
        [commentButton addTarget:self action:@selector(onClickCommentButton:) forControlEvents:UIControlEventTouchUpInside];
        [toolbar addSubview:commentButton];
    }
    
    [self.view addSubview:toolbar];
}

- (void)initWriteCommentBar
{
    UIView *writeCommentBar = [[UIView alloc] initWithFrame:CGRectMake(-1, self.view.height, self.view.width + 2, 50)];
    writeCommentBar.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:1];
    writeCommentBar.layer.borderColor = [UIColor grayColor].CGColor;
    writeCommentBar.layer.borderWidth = 1;
    
    UITextView *commentTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, self.view.width - 50 - 10, 40)];
    commentTextView.backgroundColor = [UIColor whiteColor];
    commentTextView.layer.borderWidth = 1;
    commentTextView.layer.borderColor = [UIColor grayColor].CGColor;
    commentTextView.layer.cornerRadius = 3;
    commentTextView.layer.masksToBounds = YES;
    commentTextView.font = [UIFont systemFontOfSize:14.0f];
    [writeCommentBar addSubview:commentTextView];
    self.commentTextView = commentTextView;
    
    UIButton *sendCommentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sendCommentButton.frame = CGRectMake(self.view.width - 49, 5, 44, 40);
    [sendCommentButton setBackgroundImage:[[UIImage imageNamed:@"btn_border.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(5, 5, 5, 5)] forState:UIControlStateNormal];
    [sendCommentButton addTarget:self action:@selector(onClickSendCommentButton:) forControlEvents:UIControlEventTouchUpInside];
    [sendCommentButton setTitle:@"发表" forState:UIControlStateNormal];
    [sendCommentButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    sendCommentButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [writeCommentBar addSubview:sendCommentButton];
    
    [self.view addSubview:writeCommentBar];
    self.writeCommentBar = writeCommentBar;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self addCommonBackButton];
    self.navigationItem.title = @"详情";
    
    self.webViewNews = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 44)];
    self.webViewNews.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.webViewNews];
    
    [self initToolBar];
    [self initWriteCommentBar];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.news.source_url]];
    [self.webViewNews loadRequest:request];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillChangeFrameNotification
                                                  object:nil];
}

#pragma mark -
#pragma mark Action
- (void)onClickWriteCommentButton:(id)sender
{
    [self.commentTextView becomeFirstResponder];
}

- (void)onClickCommentButton:(id)sender
{
    NewsCommentViewController *commentViewController = [[NewsCommentViewController alloc] initWithNewsId:self.news.newsId];
    [self.navigationController pushViewController:commentViewController animated:YES];
}

- (void)onClickShareButton:(id)sender
{
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:self.news.title
                                       defaultContent:self.news.brief
                                                image:[ShareSDK imageWithUrl:self.news.img]
                                                title:self.news.title
                                                  url:self.news.source_url
                                          description:self.news.brief
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    
    NSArray *shareList = [ShareSDK getShareListWithType:ShareTypeSinaWeibo,ShareTypeQQ,ShareTypeWeixiSession,ShareTypeWeixiTimeline, nil];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:shareList
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    [self showText:[NSString stringWithFormat:@"%@", [error errorDescription]]];
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                }
                            }];
}

- (void)onClickSaveButton:(id)sender
{
    if (![CurrentUser shareInstance].token) {
        [self showText:@"请先登录!" time:2];
    } else {
        [NewsNet addNewsToFavoriteWithNewsId:self.news.newsId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:@"收藏成功！" time:2];
                });
            } else {
                NSString *message = [responseObject objectForKey:@"message"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:message time:2];
                });
            }
            
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"网络连接失败" time:2];
            });
        }];
    }
}

- (void)onClickSendCommentButton:(id)sender
{
    [self.commentTextView resignFirstResponder];
    NSString *text = self.commentTextView.text;
    NSString *tempText = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (tempText.length == 0) {
        //评论不能为空
        return;
    }
    
    @weakify(self);
    [NewsNet sendNewsCommentWithNewsId:self.news.newsId comment:self.commentTextView.text successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);

        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"评论成功！" time:2];
            });
            self.commentTextView.text = nil;
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

#pragma mark -
#pragma mark Notification
- (void)keyboardWillShow:(NSNotification *)notification
{
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.25f animations:^{
        self.writeCommentBar.top = self.view.height;
    }];
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    //CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;

    [UIView animateWithDuration:0.25f animations:^{
        self.writeCommentBar.bottom = self.view.height - endKeyboardRect.size.height;
    }];
}

@end
